#!/bin/bash

# Usage example: ./install_opencv.sh --python 3.9 --opencv 4.9.0
# 使用例子：./install_opencv.sh --python 3.9 --opencv 4.9.0

usage() {
  echo "Usage: $0 [--python VERSION] [--opencv VERSION]"
  exit 1
}

# Default values
PYTHON_VERSION="3.9"
OPENCV_VERSION="4.9.0"

# Parse command line arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    --python)
      PYTHON_VERSION="$2"
      shift 2
      ;;
    --opencv)
      OPENCV_VERSION="$2"
      shift 2
      ;;
    *)
      usage
      ;;
  esac
done

# 拉取 OpenCV 仓库
git clone https://gitee.com/ksaos/opencv.git
# 进入opencv目录
cd opencv
# 检出对应版本
git checkout $OPENCV_VERSION

# 拉取 OpenCV Contrib 仓库
git clone https://gitee.com/ksaos/opencv_contrib.git
# 进入目录 opencv_contrib
cd opencv_contrib
# 检出对应版本
git checkout $OPENCV_VERSION
# 返回上一层
cd ..

# 删除编译目录
rm -rf build
# 创建编译目录
mkdir build
# 进入编译目录
cd build

# Configure OpenCV with GStreamer and Python support
cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D INSTALL_PYTHON_EXAMPLES=ON \
      -D INSTALL_C_EXAMPLES=OFF \
      -D PYTHON_EXECUTABLE=$(which python$PYTHON_VERSION) \
      -D BUILD_opencv_python2=OFF \
      -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules \
      -D CMAKE_INSTALL_PREFIX=$(python$PYTHON_VERSION -c "import sys; print(sys.prefix)") \
      -D PYTHON3_EXECUTABLE=$(which python$PYTHON_VERSION) \
      -D PYTHON3_INCLUDE_DIR=$(python$PYTHON_VERSION -c "from sysconfig import get_paths; print(get_paths()['include'])") \
      -D PYTHON3_LIBRARY=$(python$PYTHON_VERSION-config --configdir)/libpython$PYTHON_VERSION.so \
      -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python$PYTHON_VERSION -c "import numpy; print(numpy.get_include())") \
      -D PYTHON3_PACKAGES_PATH=$(python$PYTHON_VERSION -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
      -D PYTHON_LIBRARY=$(python$PYTHON_VERSION-config --configdir)/libpython$PYTHON_VERSION.so \
      -D WITH_GSTREAMER=ON \
      -D WITH_GTK=ON \
      -D BUILD_opencv_python3=ON \
      -D PYTHON_DEFAULT_EXECUTABLE=$(which python$PYTHON_VERSION) \
      -D PYTHON_EXECUTABLE=$(which python$PYTHON_VERSION) \
      -D BUILD_EXAMPLES=ON \
      ..

# 编译 OpenCV 使用当前CPU所有线程
make -j$(nproc)

# 安装 OpenCV
sudo make install

# 更新配置
sudo ldconfig

# 返回上一层
cd ..

echo "\n---------- 编译完成 ----------"
echo "\nPython Opencv版本号："
# 打印输出编译完成的cv2版本号
python$PYTHON_VERSION -c "import cv2; print(cv2.__version__)"
echo "\nPython Opencv路径："
python$PYTHON_VERSION -c "import cv2; print(cv2.__file__)"